import React, { useRef } from "react";
import { Button } from "antd";
import service from "@/service/httpAxios";
import styles from "./login.module.scss";
import { useNavigate } from "react-router";
import { useSelector } from "react-redux";
import { selectLang } from "@/redux/reducer";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import i18n from "@/assets/i18next";

const Login: React.FC = () => {
  const useNavigateTo = useNavigate();
  const nowLang = useSelector(selectLang);
  const tips = useRef<HTMLInputElement>(null);
  const admin = useRef<HTMLInputElement>(null);
  const password = useRef<HTMLInputElement>(null);

  function handleLogin() {
    const username = admin.current!.value;
    const passWord = password.current!.value;
    if (username === "" || passWord === "") {
      showTips("用户名或密码不能为空", false);
      return;
    }
    service
      .post("/user/login", {
        username: username,
        password: passWord,
      })
      .then((res: any) => {
        if (res.result.code == 200) {
          showTips(res.result.msg, true);
          localStorage.setItem("Access-token", res.result.data.accessToken);
          localStorage.setItem("Refresh-token", res.result.data.refreshToken);
          localStorage.setItem("my-lang", nowLang);
          i18n.changeLanguage(nowLang);
          setTimeout(() => {
            useNavigateTo("/home/note");
          }, 1000);
        }
      })
  }

  function showTips(msg: string, isSuccess: boolean) {
    tips.current!.innerText = msg;
    tips.current!.style.opacity = "1";
    const bgStyle = isSuccess ? "alert-success" : "alert-danger";
    tips.current!.classList.add(bgStyle);
    setTimeout(function () {
      tips.current!.style.opacity = "0";
      tips.current!.classList.remove(bgStyle);
    }, 1000);
  }

  return (
    <div className={styles.root}>
      <div className="align">
        <div className="second">
          <div className="welcome">
            <h3>欢迎-登录</h3>
            <div ref={tips} className="tips">
              登录成功
            </div>
          </div>
          <div className="admin">
            <p>账号</p>
            <div className="admin-box">
              <UserOutlined />
              <input ref={admin} id="upinput" type="text"></input>
            </div>
          </div>
          <div className="pword">
            <p>密码</p>
            <div className="admin-box">
              <LockOutlined />
              <input ref={password} id="upinput" type="password" />
            </div>
          </div>
          <Button onClick={handleLogin} type="primary" className="login">
            登 录
          </Button>
          <div className="register">
            <p onClick={() => useNavigateTo("/registe")}>没有账号，点击注册</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
